package com.tbit.uqbike.webmanager.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.common.enums.OperaPswEnum;
import com.tbit.uqbike.annos.OperateLog;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.AccountUser;
import com.tbit.uqbike.object.pojo.RideLogDetails;
import com.tbit.uqbike.object.pojo.dto.*;
import com.tbit.uqbike.object.pojo.vo.EfficientCardVO;
import com.tbit.uqbike.object.pojo.vo.RideLogDetailsSumVO;
import com.tbit.uqbike.object.pojo.vo.RideLogDetailsVO;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.common.entity.view.PageResult;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.service.business.AccountUserService;
import com.tbit.uqbike.service.business.OperaPswService;
import com.tbit.uqbike.service.business.RideLogDetailsService;
import com.tbit.uqbike.webmanager.util.MD5PasswordUtil;
import com.tbit.uqbike.webmanager.util.csv.annotations.AsyncDownload;
import com.tbit.utils.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 骑行订单接口
 *
 * @Author:BUGTian
 * @DATE: 2022/11/12
 */
@Validated
@RestController
@RequestMapping("/rideLogDetails")
public class RideLogDetailsController {

    @Autowired
    private RideLogDetailsService rideLogDetailsService;
    @Autowired
    private AccountUserService accountUserService;
    @Autowired
    private OperaPswService operaPswService;


    /**
     * 分页查询骑行订单详情
     *
     * @param queryDTO
     * @return
     */
    @GetMapping("/queryPage")
    public Result<PageResult<RideLogDetails>> queryPage(RideLogDetailsQueryDTO queryDTO) {
        Assert.notNulls("参数有误", queryDTO.getBrandId(), queryDTO.getAccountIds(), queryDTO.getStartTime(), queryDTO.getEndTime(), queryDTO.getDateQueryType(), queryDTO.getPage(), queryDTO.getSize());
        PageResult<RideLogDetails> pageResult = rideLogDetailsService.queryPage(queryDTO);
        if (Objects.nonNull(queryDTO.getRidingTimeMoreThan()) && Objects.nonNull(queryDTO.getRidingTimeLessThan()) && queryDTO.getRidingTimeMoreThan() > queryDTO.getRidingTimeLessThan() && CollectionUtil.isEmpty(pageResult.getList())){
            throw new BaseException("暂无符合条件的数据，请重新设置筛选条件");
        }
        return Result.success(pageResult);
    }

    /**
     * 骑行订单详情账单下载
     *
     * @param downloadDTO
     * @return
     */
    @AsyncDownload(defaultFileName = "骑行订单详情账单")
    @GetMapping("/download")
    public Result download(RideLogDetailsDownloadDTO downloadDTO) {
        String url = rideLogDetailsService.downloadRideLogDetail(downloadDTO);
        return Result.success(url);
    }

    /**
     * 骑行订单统计
     *
     * @param queryDTO
     * @return
     */
    @GetMapping("/sum")
    public Result<RideLogDetailsSumVO> sum(RideLogDetailsQueryDTO queryDTO) {
        Assert.notNulls("参数有误", queryDTO.getBrandId(), queryDTO.getAccountIds(), queryDTO.getStartTime(), queryDTO.getEndTime(), queryDTO.getDateQueryType());
        RideLogDetailsSumVO rideLogDetailsSumVO = rideLogDetailsService.sum(queryDTO);
        return Result.success(rideLogDetailsSumVO);
    }

    /**
     * 查询骑行记录
     *
     * @param request
     * @param phone    手机号
     * @param userCode 车辆编号
     * @return
     */
    @GetMapping("/queryCyclingRecord")
    public Result<PageResult<RideLogDetailsVO>> queryCyclingRecord(HttpServletRequest request, String phone, String userCode, @NotNull Integer page, @NotNull Integer size) {
        Assert.notNulls("分页参数有误", page, size);
        LoginInfo login = BaseController.getLogin(request);
        PageResult<RideLogDetailsVO> pageResult = rideLogDetailsService.queryCyclingRecord(login, phone, userCode, page, size);
        return Result.success(pageResult);
    }

    /**
     * 根据订单编号查询订单详情
     *
     * @param orderId 订单编号
     * @return
     */
    @GetMapping("/queryByOrderId")
    public Result<RideLogDetailsVO> queryByOrderId(@NotNull String orderId) {
        RideLogDetailsVO rideLogDetailsVO = rideLogDetailsService.queryByOrderId(orderId);
        return Result.success(rideLogDetailsVO);
    }

    /**
     * 人工结束订单
     *
     * @param request
     * @param finishOrderDTO
     * @return
     */
    @PutMapping("/finishOrder")
    @OperateLog(module = ModuleEnum.ORDER, methods = MethodEnum.ORDER_FINISH)
    public Result finishOrder(HttpServletRequest request, @RequestBody FinishOrderDTO finishOrderDTO) {
        Assert.notNulls("参数有误", finishOrderDTO.getUserId(), finishOrderDTO.getMoney(), finishOrderDTO.getRemark());
        /**操作密码校验*/
        operaPswService.checkOperaPsw(BaseController.getLogin(request), OperaPswEnum.OPERA_PSW_ORDER_CONFIG.getModule(),
                    finishOrderDTO.getPsw());

        return rideLogDetailsService.finishOrder(BaseController.getLogin(request), finishOrderDTO);
    }

    /**
     * 人工修改订单金额
     *
     * @param request
     * @param editOrderDTO
     * @return
     */
    @PutMapping("/editOrder")
    @OperateLog(module = ModuleEnum.ORDER, methods = MethodEnum.ORDER_EDIT)
    public Result editOrder(HttpServletRequest request, @RequestBody EditOrderDTO editOrderDTO) {
        Assert.notNulls("参数有误", editOrderDTO.getOrderId(), editOrderDTO.getRideMoney(), editOrderDTO.getFineMoney(),
                editOrderDTO.getPsw(), editOrderDTO.getRemark());
        /**操作密码校验*/
        operaPswService.checkOperaPsw(BaseController.getLogin(request), OperaPswEnum.OPERA_PSW_ORDER_CONFIG.getModule(),
                editOrderDTO.getPsw());

        return rideLogDetailsService.editOrder(BaseController.getLogin(request), editOrderDTO);
    }


    /**
     * 获取用户有效卡券
     * @param userId 用户id
     * @param accountId 区域id
     * @return  Result<EfficientCardVO>
     */
    @GetMapping("/getEfficientCard")
    public Result<EfficientCardVO> getEfficientCard(Integer userId, Integer accountId) {
        Assert.notNulls("参数有误", userId, accountId);
        return rideLogDetailsService.getEfficientCard(userId, accountId);
    }


    /**
     * 人工修改订单金额（运维端）
     *
     */
    @PutMapping("/rpc/editOrder")
    public Result editOrder(@RequestBody EditOrderRpcDTO dto) {
        Assert.notNulls("参数有误", dto.getOrderId(), dto.getRideMoney(), dto.getFineMoney(), dto.getPsw(), dto.getRemark(), dto.getAccountUserId());

        LoginInfo loginInfo = new LoginInfo();
        AccountUser accountUser = accountUserService.getAccountUserById(dto.getAccountUserId());
        BeanUtils.copyProperties(accountUser, loginInfo);
        return rideLogDetailsService.editOrder(loginInfo, dto);
    }

    /**
     * 清除用户骑行欠款
     * @param userId  用户id
     * @param psw     操作密钥
     */
    @PutMapping("/clearArrears")
    @OperateLog(module = ModuleEnum.ORDER, methods = MethodEnum.CLEAR_ARREARS)
    public Result<String> clearArrears(HttpServletRequest request, Integer userId, String psw) {
        /**操作密码校验*/
        operaPswService.checkOperaPsw(BaseController.getLogin(request), OperaPswEnum.OPERA_PSW_ORDER_CONFIG.getModule(), psw);

        return rideLogDetailsService.clearArrears(BaseController.getLogin(request), userId);
    }

    //给运维端远程操作
    @RequestMapping("/getByOrderId")
    public Map<String,Object> getByOrderId(@RequestBody Map<String, Object> map) {
        boolean result = MD5PasswordUtil.signCheck(map.get("sign").toString(), Long.parseLong(map.get("date").toString()), map.get("param").toString());
        if (!result) {
            throw new BaseException("签名校验失败");
        }
        String orderId = (String) map.get("orderId");
        RideLogDetailsVO rideLogDetailsVO = rideLogDetailsService.queryByOrderId(orderId);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("data", rideLogDetailsVO);
        return stringObjectHashMap;
    }

}
